<template>
  <div class="page-wrap">
    <div class="top-wrap">
      机台1
      <el-select style="width: 180px; margin: 0 6px" v-model="mid" placeholder="请选择" @change="handleSearchBtnClick">
        <el-option
          v-for="item in [{ label: '1234567890ABCDEF', value: '1234567890ABCDEF' }]"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button @click="handleSearchBtnClick" slot="append" icon="el-icon-search"> 检索</el-button>
    </div>
    <div class="charts">
      <div ref="ct" class="chart-wrap"></div>
    </div>
  </div>
</template>
<script>
import BlockTitle from '@/components/BlockTitle/index.vue'
import request from '@/utils/request'
import dayjs from 'dayjs'
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme

function minuteToCh(t) {
  let timeStr = ''
  let converted = Math.floor(t / (24 * 60))
  if (converted > 0) timeStr += `${converted}天`
  t = t % (24 * 60)
  converted = Math.floor(t / 60)
  if (converted > 0) timeStr += `${converted}小时`
  t = t % 60
  if (t > 0) timeStr += `${t}分钟`
  return timeStr
}
const animationDuration = 6000
var spinlist = [{ label: '全部', value: '全部' }]
for (let i = 1; i < 100; i++) {
  spinlist.push({ label: i, value: i })
}
//console.log(BlockTitle)
export default {
  name: 'MachineInfoRun',
  components: {
    BlockTitle,
    Gap: {
      template: `<div style="width:10px"></div>`,
    },
    GapX: {
      template: `<div style="width:20px"></div>`,
    },
  },
  filters: {
    toTime(t) {
      return t ? dayjs(t).format('MM-DD HH:mm:ss') : '-'
    },

    twoNum(e) {
      return (e < 10 ? '0' : '') + e
    },
    thrNum(e) {
      return ('000' + e).slice(-3)
    },
    toDotTime(r) {
      const now = r.endTime ? dayjs(r.endTime) : dayjs()
      let t = now.diff(r.startTime, 'second')
      let timeStr = ''
      let converted = Math.floor(t / (24 * 60 * 60))
      if (converted > 0) timeStr += `${converted}天`
      t = t % (24 * 60 * 60)
      converted = Math.floor(t / (60 * 60))
      if (converted > 0) timeStr += `${converted}时`
      t = t % (60 * 60)
      converted = Math.floor(t / 60)
      if (converted > 0) timeStr += `${converted}分`
      converted = t % 60

      if (converted > 0) timeStr += `${converted}秒`
      return timeStr
    },
  },
  data() {
    return {
      except: '全部',
      timeRange: [],
      colorMap: {
        落纱: '#FFA939',
        纺纱: '#00DBAA',
        停机: '#7F9AAF',
        离线: '#FF6155',
      },
      spinNum: '全部',
      spinlist,
      mid: '1234567890ABCDEF',
      sqlList: [
        {
          value: `select * from spin_exceptional where mid='000000000000000001' and inx = 0 order by side,inx,type,startTime `,
          label: 'all',
        },
      ],
      exceptChr: [
        { label: '0-断头', value: 0 },
        { label: '1-掉线', value: 1 },
        { label: '2-闲置', value: 2 },
        { label: '3-弱捻', value: 3 },
        { label: '4-严重弱捻', value: 4 },
        { label: '5-锭子故障', value: 5 },
        { label: '全部', value: '全部' },
      ],
      // exceptChr: ['0-断头', '1-掉线', '2-闲置', '3-弱捻', '4-严重弱捻', '5-锭子故障'],
      leftPageInfo: { pageSize: 100, pageNum: 1 },
      rightPageInfo: { pageSize: 100, pageNum: 1 },
      customColWidth: {
        id: 150,
        PackType: 80,
        Side: 60,
        SpinStartAddr: 70,
        SpinNumber: 60,
      },
      workshops: ['车间1', '车间2', '车间3'],
      macLis: [],
      macDetail: {},
      currentMac: '',
      currentWorkshop: '',
      dataList: [],
      propList: [],
      leftData: [],
      rightData: [],
      currentRow: '',
      pageInfo: [],
    }
  },
  computed: {},
  created() {
    this.getData()
    // const defaultSqlList = localStorage.getItem('sqlList_except')
    // if (defaultSqlList) this.sqlList = JSON.parse(defaultSqlList)
    // const defaultSql = localStorage.getItem('defaultSql_except')
    // if (defaultSql) this.sql = this.defaultSql = defaultSql
  },
  mounted() {
    window.dj = dayjs
    //console.log(dayjs)
    // this.$nextTick(() => {
    //   this.initChart()
    // })
  },
  methods: {
    initChart(series) {
      this.chart = echarts.init(this.$refs.ct, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: '#999',
              width: 1,
              type: 'dashed',
            },
          },
          backgroundColor: '#fff',
          extraCssText: 'box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);',
          padding: [10, 15],
          textStyle: {
            fontFamily: 'Arial',
            color: '#333',
          },
          formatter: function (params) {
            let result = `${params[0].axisValueLabel}</br>`
            params.forEach(function (item) {
              result += `<div style="text-align:left">${item.marker} ${item.seriesName}<b style="float:right">${item.value}</b></div>`
            })
            return result
          },
        },
        legend: {
          top: '0%',
          data: ['新增断头', '速度'],
        },
        grid: {
          left: '2%',
          right: '2%',
          top: '8%',
          bottom: '2%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data: series.time,
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '新增断头',
            axisLine: {
              lineStyle: {
                color: '#00adff',
              },
            },
            splitArea: {
              show: false,
            },
          },
          {
            type: 'value',
            name: '速度(rpm)',
            axisLine: {
              lineStyle: {
                color: '#f57676',
              },
            },
            splitArea: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: '新增断头',
            type: 'bar',
            barWidth: '10px',
            itemStyle: {
              color: '#00adff',
            },
            tooltip: {
              valueFormatter: function (value) {
                return value
              },
            },
            data: series.broken,
          },
          {
            name: '速度',
            type: 'line',
            smooth: false,
            yAxisIndex: 1,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: {
              color: '#f57676',
              shadowColor: '#f57676',
              shadowBlur: 8,
            },
            tooltip: {
              valueFormatter: function (value) {
                return value
              },
            },
            data: series.speed,
          },
        ],
      })
    },
    handleSearchBtnClick() {
      this.getData()
    },
    handleSizeChange(e, side) {
      console.log('handleSizeChange', e)
      if (side == 'Left') {
        this.leftPageInfo.pageSize = e
      } else {
        this.rightPageInfo.pageSize = e
      }
      this.getData(side)
    },
    handleCurrentChange(e, side) {
      if (side == 'Left') {
        this.leftPageInfo.pageNum = e
      } else {
        this.rightPageInfo.pageNum = e
      }
      this.getData(side)
    },
    async getData(side) {
      console.log(111)

      let sql = `SELECT * FROM [lce].[dbo].[v_mac_status] order by newsj desc`
      const { mid, except, currentRow, spinNum } = this
      console.log(this.currentRow, this.spinNum)
      this.$ShowLoading()
      // const loading = this.$loading({
      //   lock: true,
      //   text: `正在加载数据`,
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)',
      // })
      let pageInfo = this.leftPageInfo
      try {
        const { pageNum: pagenum, pageSize: pagesize } = pageInfo
        const res = await request({
          url: '/db/getData',
          method: 'post',
          // data: {
          //   spName: 'sp_dtbb',
          //   params: [
          //     { isnum: false, value: '2024-03-01' },
          //     { isnum: true, value: 123 },
          //   ],
          //   pagenum: 1,
          //   pagesize: 20,
          // },
          data: { sql, pagenum, pagesize },
        })
        if (res.obj.list.length == 0) {
          // loading.close()
          return
        }

        this.leftPageInfo = { ...res.obj }
        // if (side == 'Left') {
        this.leftData = res.obj.list
      } catch (e) {
        console.log('Error:', e)
      } finally {
        this.$CloseLoading()
      }
      sql = `SELECT * FROM [lce].[dbo].[v_mac_status] where newsj > convert(varchar(10),getdate(),120) order by newsj desc`
      this.$ShowLoading()
      try {
        const res = await request({
          url: '/db/getDataBySp',
          method: 'post',
          data: {
            spName: 'sp_dtbb',
            params: [
              { isnum: false, value: dayjs(this.toDate).format('YYYY-MM-DD') },
              { isnum: true, value: 50 },
            ],
            pagenum: 1,
            pagesize: 20,
          },
        })
        const series = {
          time: res.list && Array.isArray(res.list) ? res.list.map((item) => dayjs(item.start_time).format('YYYY-MM-DD HH:mm:ss')) : [],
          broken: res.list && Array.isArray(res.list) ? res.list.map((item) => item.broken) : [],
          speed: res.list && Array.isArray(res.list) ? res.list.map((item) => item.speed) : [],
        }
        this.initChart(series)

        console.warn(res)
      } catch (e) {
        console.log('getdata request2 err:', e)
      } finally {
        this.$CloseLoading()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '~@/styles/variables.scss';

.page-wrap {
  padding: 10px 20px;
  box-sizing: border-box;
}

.sub-item {
  width: 44px;
  text-align: center;
  border-right: 1px #eee solid;
  flex-shrink: 0;
}

.top-wrap {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.charts {
  margin-top: 10px;
  height: calc(100vh - 170px);
  display: flex;
}

.charts-inner {
  width: 539px;
}
.chart-wrap {
  width: 100%;
  height: calc(100vh - 170px);
}
</style>
